﻿package foli
{	
	import foli.Album;
	import foli.GalleryEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;

	import sk.prasa.webapis.picasa.PicasaService;
	import sk.prasa.webapis.picasa.events.PicasaEvent;
	import sk.prasa.webapis.picasa.Album;
	import sk.prasa.webapis.picasa.GPhoto;
	
	/**
		Gallery class capable of loading data from Picasa
		
	**/
	public class Gallery extends EventDispatcher
	{
		/// picasa user
		private var _user_id: String; 		
		
		/// construct from user name
		public function Gallery( uid: String )
		{
			_user_id = uid;			
		}
		
		/// load asyncronously information about all albums available in this gallery
		public function loadAlbumList():void
		{
			var service: PicasaService = new PicasaService();
			service.addEventListener(PicasaEvent.ALBUMS_GET_LIST, this.handleAlbumList);			
			service.albums.list(_user_id);			
		}
		
		/// callback for album load
		private function handleAlbumList(evt:PicasaEvent)
		{			
			if (evt.success)
			{				
				var numAlbums: int = evt.data.length;    
				
				// for each album in the result array
				for(var i:Number = 0; i < numAlbums; i++)
				{
					var a: sk.prasa.webapis.picasa.Album = evt.data[i];
					var g: sk.prasa.webapis.picasa.GPhoto = a.gphoto;						
					
					// create new album and inform listeners
					var d: foli.Album = new foli.Album( _user_id, g.id );
					dispatchEvent( new GalleryEvent(GalleryEvent.ALBUM_ADDED, d) );
				}				
			}
			else
			{
				trace(evt.error.message);
			}
			
			// remove listener
			evt.target.removeEventListener( evt.type, this.handleAlbumList );
		}	
		
	}	
}